import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { Notification } from '@/types/common';

interface Modal {
  id: string;
  component: string;
  props?: Record<string, any>;
  backdrop?: boolean;
  closable?: boolean;
}

interface Toast {
  id: string;
  type: 'success' | 'error' | 'warning' | 'info';
  title: string;
  message?: string;
  duration?: number;
  timestamp: number;
}

interface UIState {
  // Layout
  sidebarCollapsed: boolean;
  sidebarVisible: boolean;

  // Loading states
  globalLoading: boolean;
  loadingStates: Record<string, boolean>;

  // Modals
  modals: Modal[];

  // Toast notifications
  toasts: Toast[];

  // Notifications
  notifications: Notification[];
  unreadNotificationCount: number;

  // Navigation
  currentPage: string;
  breadcrumbs: Array<{ label: string; path?: string }>;

  // Theme
  theme: 'light' | 'dark' | 'system';

  // Responsive
  isMobile: boolean;
  screenWidth: number;
  screenHeight: number;

  // Drag & Drop
  isDragOver: boolean;
  draggedFiles: File[];

  // Selection
  selectedItems: string[];

  // Search
  searchQuery: string;
  searchResults: any[];
  isSearching: boolean;

  // Preferences
  preferences: {
    showTutorial: boolean;
    autoPlayVideo: boolean;
    showFileExtensions: boolean;
    confirmDeletion: boolean;
    rememberWindowState: boolean;
  };
}

const initialState: UIState = {
  // Layout
  sidebarCollapsed: false,
  sidebarVisible: true,

  // Loading
  globalLoading: false,
  loadingStates: {},

  // Modals & Toasts
  modals: [],
  toasts: [],

  // Notifications
  notifications: [],
  unreadNotificationCount: 0,

  // Navigation
  currentPage: 'dashboard',
  breadcrumbs: [],

  // Theme
  theme: 'system',

  // Responsive
  isMobile: false,
  screenWidth: window.innerWidth,
  screenHeight: window.innerHeight,

  // Drag & Drop
  isDragOver: false,
  draggedFiles: [],

  // Selection
  selectedItems: [],

  // Search
  searchQuery: '',
  searchResults: [],
  isSearching: false,

  // Preferences
  preferences: {
    showTutorial: true,
    autoPlayVideo: false,
    showFileExtensions: true,
    confirmDeletion: true,
    rememberWindowState: true,
  },
};

const uiSlice = createSlice({
  name: 'ui',
  initialState,
  reducers: {
    // Layout actions
    toggleSidebar: state => {
      state.sidebarCollapsed = !state.sidebarCollapsed;
    },
    setSidebarCollapsed: (state, action: PayloadAction<boolean>) => {
      state.sidebarCollapsed = action.payload;
    },
    setSidebarVisible: (state, action: PayloadAction<boolean>) => {
      state.sidebarVisible = action.payload;
    },

    // Loading actions
    setGlobalLoading: (state, action: PayloadAction<boolean>) => {
      state.globalLoading = action.payload;
    },
    setLoading: (state, action: PayloadAction<{ key: string; loading: boolean }>) => {
      const { key, loading } = action.payload;
      if (loading) {
        state.loadingStates[key] = true;
      } else {
        delete state.loadingStates[key];
      }
    },

    // Modal actions
    showModal: (state, action: PayloadAction<Omit<Modal, 'id'> & { id?: string }>) => {
      const modal = {
        id: action.payload.id || `modal-${Date.now()}`,
        ...action.payload,
      };
      state.modals.push(modal);
    },
    hideModal: (state, action: PayloadAction<string>) => {
      state.modals = state.modals.filter(modal => modal.id !== action.payload);
    },
    hideAllModals: state => {
      state.modals = [];
    },

    // Toast actions
    showToast: (
      state,
      action: PayloadAction<Omit<Toast, 'id' | 'timestamp'> & { id?: string }>
    ) => {
      const toast = {
        id: action.payload.id || `toast-${Date.now()}`,
        timestamp: Date.now(),
        duration: action.payload.duration ?? 5000,
        ...action.payload,
      };
      state.toasts.push(toast);
    },
    hideToast: (state, action: PayloadAction<string>) => {
      state.toasts = state.toasts.filter(toast => toast.id !== action.payload);
    },
    clearToasts: state => {
      state.toasts = [];
    },

    // Notification actions
    addNotification: (state, action: PayloadAction<Notification>) => {
      state.notifications.unshift(action.payload);
      state.unreadNotificationCount++;

      // Keep only last 50 notifications
      if (state.notifications.length > 50) {
        state.notifications = state.notifications.slice(0, 50);
      }
    },
    removeNotification: (state, action: PayloadAction<string>) => {
      const index = state.notifications.findIndex(n => n.id === action.payload);
      if (index >= 0) {
        state.notifications.splice(index, 1);
        if (state.unreadNotificationCount > 0) {
          state.unreadNotificationCount--;
        }
      }
    },
    markNotificationsRead: state => {
      state.unreadNotificationCount = 0;
    },
    clearNotifications: state => {
      state.notifications = [];
      state.unreadNotificationCount = 0;
    },

    // Navigation actions
    setCurrentPage: (state, action: PayloadAction<string>) => {
      state.currentPage = action.payload;
    },
    setBreadcrumbs: (state, action: PayloadAction<Array<{ label: string; path?: string }>>) => {
      state.breadcrumbs = action.payload;
    },

    // Theme actions
    setTheme: (state, action: PayloadAction<'light' | 'dark' | 'system'>) => {
      state.theme = action.payload;
    },

    // Responsive actions
    setScreenSize: (state, action: PayloadAction<{ width: number; height: number }>) => {
      state.screenWidth = action.payload.width;
      state.screenHeight = action.payload.height;
      state.isMobile = action.payload.width < 768;
    },

    // Drag & Drop actions
    setDragOver: (state, action: PayloadAction<boolean>) => {
      state.isDragOver = action.payload;
    },
    setDraggedFiles: (state, action: PayloadAction<File[]>) => {
      state.draggedFiles = action.payload;
    },
    clearDraggedFiles: state => {
      state.draggedFiles = [];
      state.isDragOver = false;
    },

    // Selection actions
    setSelectedItems: (state, action: PayloadAction<string[]>) => {
      state.selectedItems = action.payload;
    },
    selectItem: (state, action: PayloadAction<string>) => {
      if (!state.selectedItems.includes(action.payload)) {
        state.selectedItems.push(action.payload);
      }
    },
    deselectItem: (state, action: PayloadAction<string>) => {
      state.selectedItems = state.selectedItems.filter(id => id !== action.payload);
    },
    toggleItemSelection: (state, action: PayloadAction<string>) => {
      const index = state.selectedItems.indexOf(action.payload);
      if (index >= 0) {
        state.selectedItems.splice(index, 1);
      } else {
        state.selectedItems.push(action.payload);
      }
    },
    clearSelection: state => {
      state.selectedItems = [];
    },

    // Search actions
    setSearchQuery: (state, action: PayloadAction<string>) => {
      state.searchQuery = action.payload;
    },
    setSearchResults: (state, action: PayloadAction<any[]>) => {
      state.searchResults = action.payload;
    },
    setSearching: (state, action: PayloadAction<boolean>) => {
      state.isSearching = action.payload;
    },
    clearSearch: state => {
      state.searchQuery = '';
      state.searchResults = [];
      state.isSearching = false;
    },

    // Preferences actions
    updatePreference: (
      state,
      action: PayloadAction<{ key: keyof UIState['preferences']; value: boolean }>
    ) => {
      const { key, value } = action.payload;
      state.preferences[key] = value;
    },
    updatePreferences: (state, action: PayloadAction<Partial<UIState['preferences']>>) => {
      state.preferences = { ...state.preferences, ...action.payload };
    },
  },
});

export const {
  // Layout
  toggleSidebar,
  setSidebarCollapsed,
  setSidebarVisible,

  // Loading
  setGlobalLoading,
  setLoading,

  // Modals
  showModal,
  hideModal,
  hideAllModals,

  // Toasts
  showToast,
  hideToast,
  clearToasts,

  // Notifications
  addNotification,
  removeNotification,
  markNotificationsRead,
  clearNotifications,

  // Navigation
  setCurrentPage,
  setBreadcrumbs,

  // Theme
  setTheme,

  // Responsive
  setScreenSize,

  // Drag & Drop
  setDragOver,
  setDraggedFiles,
  clearDraggedFiles,

  // Selection
  setSelectedItems,
  selectItem,
  deselectItem,
  toggleItemSelection,
  clearSelection,

  // Search
  setSearchQuery,
  setSearchResults,
  setSearching,
  clearSearch,

  // Preferences
  updatePreference,
  updatePreferences,
} = uiSlice.actions;

export default uiSlice.reducer;
